package com.myhome.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.enums.ApiErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.myhome.domain.LoginResult;
import com.myhome.domain.SysMenu;
import com.myhome.feign.JwtToken;
import com.myhome.feign.Oauth2FeignClient;
import com.myhome.service.SysMenuService;
import com.myhome.service.SysUserLoginService;
import com.myhome.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author QYiXin
 * @Date 2021 10 09 17 45
 **/
@Service
public class SysUserLoginServiceImpl implements SysUserLoginService {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    Oauth2FeignClient oauth2FeignClient;
    @Autowired
    SysMenuService sysMenuService;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public LoginResult userLogin(String username,String password) {
        ResponseEntity<JwtToken> result = oauth2FeignClient.getToken("password", username, password, "adminLogin", "Basic Y2xpZW50OjExMTExMQ==");
        if (result.getStatusCode()!=HttpStatus.OK) {
            throw new ApiException(ApiErrorCode.FAILED);
        }
        JwtToken jwttoken = result.getBody();
        String accessToken = jwttoken.getAccessToken();
        Jwt jwtObject = JwtHelper.decode(accessToken);
        String claims = jwtObject.getClaims();
        JSONObject object = JSON.parseObject(claims);
        String name = object.getString("user_name");
        JSONArray authorities = object.getJSONArray("authorities");
        List<SimpleGrantedAuthority> authorityList = authorities.stream().map(authority -> new SimpleGrantedAuthority(authority.toString())).collect(Collectors.toList());
        Long userId = Long.valueOf(name);
        System.out.println(userId);
        List<SysMenu> menus = sysMenuService.getMenusByUserId(userId);
        redisTemplate.opsForValue().set(accessToken,"", Long.parseLong(jwttoken.getExpiresIn()), TimeUnit.SECONDS);
        return new LoginResult(jwttoken.getTokenType()+" "+accessToken, menus, authorityList);
    }
}
